import { ViewUtil } from "db://app-game/core/utils/ViewUtil";
import { ecs } from "db://app-game/libs/ecs/ECS";
import { RoleAttarModelComp } from "./model/RoleAttarModelComp";
import { RoleCollisionModelComp } from "./model/RoleCollisionModelComp";
import { RoleControlComp } from "./model/RoleControlComp";
import { RoleModelComp } from "./model/RoleModelComp";
import { RoleMoveModelComp } from "./model/RoleMoveModelComp";
import { RoleLoadParamsType } from "./Role.type";
import { RoleViewComp } from "./view/RoleViewComp";
import { app } from "db://app-game/core/app";
import { GameEvent } from "../../common/config/GameEvent";

/** 角色 */
@ecs.register("Role")
export class Role extends ecs.Entity {
  // 数据层
  RoleModel!: RoleModelComp;
  RoleAttarModel!: RoleAttarModelComp;

  // 业务层
  RoleMoveModel!: RoleMoveModelComp;
  RoleCollisionModel!: RoleCollisionModelComp;
  RoleControl!: RoleControlComp;

  // 视图层
  RoleView!: RoleViewComp;

  init() {
    this.addComponents<ecs.Comp>(
      RoleModelComp,
      RoleMoveModelComp,
      RoleCollisionModelComp,
      RoleControlComp,
      RoleAttarModelComp
    );
  }

  load(res: RoleLoadParamsType) {
    const { userId, id, parent, pos } = res;
    // 1.初始化角色数据
    this.RoleModel.id = id;
    this.RoleModel.userId = userId;

    // 2.加载角色视图
    const { data } = this.RoleModel;
    let node = ViewUtil.createPrefabNode(data.prefabPath);
    let mv = node.getComponent(RoleViewComp);
    this.add(mv);

    node.parent = parent;
    node.setPosition(pos);

    // 3.设置基础组件数据
    this.RoleModel.node = node;

    // 4.初始化角色属性
    this.initRoleAttar();
  }

  /** 初始化角色属性 */
  initRoleAttar() {
    const { data } = this.RoleModel;
    this.RoleAttarModel.speed = data.speed;
  }

  /** 切换武器 */
  switchWeapon(res: { lowerBody: string; upperBody: string }) {
    this.RoleView.lowerBody.armatureName = res.lowerBody;
    this.RoleView.upperBody.armatureName = res.upperBody;
    const upperBodyUiBlack =
      this.RoleModel.data.anim.upperBody.uiBlackList[res.upperBody];
    const lowerBodyUiBlack =
      this.RoleModel.data.anim.lowerBody.uiBlackList[res.lowerBody];
    const params = {
      joysitick: [...upperBodyUiBlack.joysitick, ...lowerBodyUiBlack.joysitick],
      skillIcon: [...upperBodyUiBlack.skillIcon, ...lowerBodyUiBlack.skillIcon],
    };
    app.message.dispatchEvent(GameEvent.RoleWeaponChange, params);
  }

  /** 释放技能 */
  triggerSkill(skillId: number) {
    this.RoleView.animatorSwitchManage.upperSkill(skillId);
  }
}
